package main

import (
	"fmt"
	"net"
	"net/http"
	"serve/bin"
	"serve/controller"
	"serve/cors"
	"serve/model"

	assetfs "github.com/elazarl/go-bindata-assetfs"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/sqlite"
)

func InitDB() {

	// dbDriver := "mysql"
	// dbUser := "root"
	// dbPass := "123456"
	// dbName := "svg"
	// db, err := gorm.Open(dbDriver, dbUser+":"+dbPass+"@tcp(127.0.0.1:3306)/"+dbName+"?charset=utf8&parseTime=true")
	db, err := gorm.Open("sqlite3", "./test.db")
	if err != nil {
		fmt.Println(err)
		panic("连接数据库失败")
	}
	// defer db.Close()
	// 自动迁移模式
	db.AutoMigrate(&model.Project{}, &model.Iteration{}, &model.Svg{})
	model.DB = db
}

func GetOutboundIP() string {
	conn, err := net.Dial("udp", "8.8.8.8:80")
	defer conn.Close()
	if err != nil {
		return ""
	}
	localAddr := conn.LocalAddr().(*net.UDPAddr)
	return localAddr.IP.String()
}

func main() {

	InitDB()
	port := ":8087"
	ip := GetOutboundIP()
	var url string
	if len(ip) > 0 {
		url = "http://" + ip + port
	} else {
		url = "http://localhost" + port
	}
	fmt.Println(url)
	// 有GUI调用
	// exec.Command(`cmd`, `/c`, `start`, url).Start()
	r := gin.Default()
	r.StaticFS("/static/", &assetfs.AssetFS{Asset: bin.Asset, AssetDir: bin.AssetDir, AssetInfo: bin.AssetInfo, Prefix: "/static"})
	r.GET("/", func(context *gin.Context) {
		//设置响应状态
		context.Writer.WriteHeader(http.StatusOK)
		//载入首页
		indexHTML, _ := bin.Asset("index.html")
		context.Writer.Write(indexHTML)
		//响应HTML类型
		context.Writer.Header().Add("Accept", "text/html")
		//显示刷新
		context.Writer.Flush()
	})
	r.Use(cors.Cors())
	controller.RegisterRouter(r)
	// r.POST("/message/add", controller.Insert)
	// r.GET("/message/parent", controller.Parent)
	// r.GET("/message/childs", controller.Childs)

	// r.GET("/check/list", controller.Show)
	// r.GET("/check/state", controller.Check)
	// r.GET("/info", controller.GetRow)
	// r.POST("/insert", controller.Insert)
	// r.POST("/update", controller.Update)
	// r.POST("/del/:id", controller.DeletePerson)
	r.Run(port)
}

// go build -ldflags="-H windowsgui  -w -s" -o ./gomange.exe .\main.go

// C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
